<?php
declare (strict_types=1);

namespace app\common\listener;

use app\common\model\SummaryDate;
use app\common\model\SummaryUser;

class Summary
{
    public function handle($data): void
    {
        $this->summaryUser($data);
    }

    public function summaryDate($data): void
    {
        $ymd = date('Y-m-d');
        $key = $data['key'];
        $info = SummaryDate::where('create_date', $ymd)->find();
        if ($info) {
            $info->$key = round(floatval($info->$key) + floatval($data['value']), 2);
            $info->save();
        } else {
            SummaryDate::create([$key => $data['value'], 'create_date' => $ymd]);
        }
    }

    public function summaryUser($data): void
    {
        $ymd = date('Y-m-d');
        $key = $data['key'];
        $info = SummaryUser::where(['create_date' => $ymd, 'uid' => $data['uid']])->find();
        if ($info) {
            $info->$key = round(floatval($info->$key) + floatval($data['value']), 2);
            $info->save();
        } else {
            SummaryUser::create([$key => $data['value'], 'create_date' => $ymd, 'uid' => $data['uid']]);
        }
        $this->summaryDate($data);
    }
}